import React, {Component} from 'react'

import {Link} from 'react-router-dom'

import { Tag,Button } from 'antd';

import moment from 'moment';

import { Row, Col,DatePicker,TimePicker,Modal,message,Select,Icon} from 'antd';

import api from './ajaxaction'

import './info.css'

import Table from '../../common/table'

import { connect } from 'react-redux'

import {inforesult,tabdata,changepos,changeSco,changesec,clearAll,pageSize,dataDelete,exportId,changType,websitetypelist,tagchange} from '../../actions/info'




const confirm = Modal.confirm

const Tendency=['全部','负面','中性','正111面']

const browse=['全部','已阅','未阅']

const chunk =['列表','摘要']


const rangeCoury =['全部','全国','本地','境外']

const showoff =['展开','合并']

const sortList =['时间降序','时间升序','相关性排序']


class TagList extends Component{
  constructor(props){
    super(props);
    this.state={
    }
  }
  handleclear(){
    let arrData=this.props.tagList
    arrData=[]
    this.props.update(arrData)
    this.props.cleartypeall([0,0,0,0,0,0,0])
  }
  render(){
    return(
      <div className="tag">
          <div className="tag-li">
            {
              this.props.tagList.map((item,i)=>(
                <Tag closable key={i}>{item}</Tag>
              ))
            }
          </div>
          <span onClick={()=>this.handleclear()}>清除全部</span>
        </div>
    )
  }
}
//顶部类型选择
class Tabchose extends Component{
  constructor(props){
    super(props);
    this.state={
      currentHtml:'',
      currentIndex:0
    }
  }
  handleChoes(e){
    var oIndex= Number(e.target.getAttribute('data-key'))
    var key=this.props.number
    var oValue=e.target.innerHTML
    let tablist=this.props.result
    let arr=this.props.choselist;
    arr[key]=oIndex
    this.props.tagchag(arr)
    if(oIndex===0){
      tablist.splice(key,1)
    }else{
      tablist[key]=oValue
    }
    this.setState({
      currentIndex:oIndex
    })
    this.props.onAdd(tablist,oValue)
    if(oValue==="列表"){
      this.props.changeabs(false)
    }else if(oValue==="摘要"){
      this.props.changeabs(true)
    }
    if(this.props.number==="1"){
      if(oValue==="已阅"){
        this.props.changeabs(0)
      }else if(oValue==="未阅"){
        this.props.changeabs(1)
      }else{
        this.props.changeabs(-1)
      }
    }

    if(oValue==="合并" ){
      this.props.assignField('titleContentPrint','count')
    }else if(oValue==="展开"){
      this.props.assignField(' ','all')
    }
  }
  render(){
    let dietypelist=Object.assign([],this.props.tabli)
    if(this.props.typeid==="dir"){
      return(
        <div className="label-li">
        <label>{this.props.title}：</label>
        <div className="tab">
            {
              dietypelist.splice(0,4).map((item,i)=>{
                if(this.props.choselist[this.props.number]===i){
                  return(
                    <span className={'active'} data-key={i} key={i}>{item}</span>
                  )

                }else{
                  return(
                    <span onClick={(e)=>this.handleChoes(e)} data-key={i} key={i}>{item}</span>
                  ) 
                }
              })
            }
          </div>
        <div className="tab add">
            <Icon type="plus-circle-o" style={{color:'#007be2',fontSize:'14px'}}></Icon>
            <Link to="/directional">添加</Link>
        </div>
      </div>
      )
    }else{
      return(
        <div className="label-li">
          <label>{this.props.title}：</label>
          <div className="tab">
            {
              this.props.tabli.map((item,i)=>{
                if(this.props.choselist[this.props.number]===i){
                  return(
                    <span className={'active'} data-key={i}  key={i}>{item}</span>
                  )

                }else{
                  return(
                    <span onClick={(e)=>this.handleChoes(e)} data-key={i}  key={i}>{item}</span>
                  ) 
                }
              })
            }
          </div>
        </div>
      )
    }

  }
}


// 中部类型选择
class Taball extends Component{
  constructor(props){
    super(props);
    this.state={
      currentIndex:0
    }
  }
  handle(e){
    var oIndex= Number(e.target.getAttribute('data-key'))
    let id=Number(e.target.getAttribute('data-id'))
    this.setState({
      currentIndex:oIndex
    })
    this.props.changereasult(id)
  }

  render(){
    let list=Object.assign([],this.props.tanList)
    let newLi=list.splice(-1,1)
    list=newLi.concat(list)
    return(
      <div className="typeli">
        {
          list.map((item,i)=>(
              <div className={i===this.state.currentIndex?'active':''} onClick={(e)=>this.handle(e)} data-key={i} data-id={item.key} key={i}>{item.webSiteName}({item.doc_count})</div>
          ))
        }
      </div>
    )
  }
}

@connect(
  state => state.inforesult,
  {inforesult,tabdata,changepos,changeSco,changesec,clearAll,pageSize,dataDelete,exportId,changType,websitetypelist,tagchange}
)

// 整体
class Info extends Component{
  constructor(props){
    super(props);
    this.state={
      tableData:[],
      tagList:[],
      decList:[],
      tanList:['全部','新闻','论坛','微信','手机App','微博','平面媒体','博客','贴吧'],
      loading:true,
      isFirst:true,
      startData:this.startTime(),
      endData:this.endTime(),
      startTime:this.startTime()+" 00:00:00",
      endTime:this.endTime()+" "+this.nowTime()+":00",
      sortType:'desc',
      scope:-1,
      websiteType :-1,
      positiveOrNegative:-1,
      currentPage:1,
      limit:50,
      sortField:'poTime',
      abroad:-1,
      categoryId:'',
      searchType:"all",
      topicId:"",
      deleteArr:[],
      readArr:[],
      abstract:false,
      aggsField:'',
      ishas:false,
      ceshi:true,
      direcList:[],
      isRead:-1,
      selectedRowKeys: [],
    }
    this.onChange=this.onChange.bind(this)
    this.onChangestime=this.onChangestime.bind(this)
    this.onChangend=this.onChangend.bind(this)
    this.onChangeendtime=this.onChangeendtime.bind(this)
    this.taghandchange=this.taghandchange.bind(this)
  }
  startTime(){
    return moment().format('YYYY-MM-DD')
  }
  endTime(){
    return moment().format('YYYY-MM-DD')
  }
  nowTime(){
    return moment().format('HH:mm')
  }


  //数据接口
  renderTabledata(){
    this.props.tabdata(
      this.state.startTime,
      this.state.endTime,
      this.props.positiveOrNegative,
      this.props.scope,
      this.props.sortType,
      this.props.sortField,
      this.props.isFirst,
      this.props.limit,
      this.state.websiteType,
      this.state.currentPage,
      this.state.aggsField,
      this.state.searchType,
    )
  }

  //数据来源
  webType(){
    this.props.websitetypelist(
      this.state.startTime,
      this.state.endTime,
      this.props.positiveOrNegative,
      this.props.scope,
      this.props.sortType,
      this.props.sortField,
      this.props.isFirst,
      this.props.limit,
      this.state.websiteType,
      this.state.currentPage,
      this.state.aggsField,
      this.state.searchType,
    )
  }
  componentDidMount(){
    this.webType()
    this.renderTabledata()
    this.renderdirec()
  }

  handleclear(){

  }
  onchangeSize(value){
    this.props.pageSize(value)
  }
  sureBtn(){
    this.webType()
    this.renderTabledata()
  }

  //筛选条件增减
  async condChange(result){
      this.setState({
        tagList:result
      }
    )
    await this.props.clearAll()
    await this.webType()
    await this.renderTabledata()
    
  }
  async posChange(value,k){
    await this.props.changepos(value,k);
    await this.renderTabledata()
  }
  async posChange1(value,k){
    await this.props.changeSco(value,k);
    await this.renderTabledata()
  }
  async posChange2(value,k){

    await this.props.changesec(value,k);
    await this.renderTabledata()
  }
  //开始日期
  onChange(date,dateString){
    this.setState({
      startTime:dateString+" 00:00:00",
      startData:dateString
    })
  }
  //结束日期
  onChangend(data,dateString){
    this.setState({
      endTime:dateString+" "+this.nowTime()+":00",
      endData:dateString
    })
  }
  //开始时间
  onChangestime(time, timeString){
    this.setState({
      startTime:this.state.startData+" "+timeString+":00"
    })
  }
  //结束时间
  onChangeendtime(time, timeString){
    this.setState({
      endTime:this.state.endData+" "+timeString+":00"
    })
  }
  //删除

  tableAction(actionKey){
    if(actionKey==="删除"){
      confirm({
        title: '提示',
        content: '确定删除吗',
        onOk: () => {
            this.webType()
            this.renderTabledata()
            message.success('删除成功')
        },
        onCancel() {
          return false
        }
      })
    }else if(actionKey==="收藏"){
      api.joinCollection('vrv-monitor-platform-web/collection/insert',this.id,this.tit,this.content,this.poTime,this.webSite,this.domain,this.positiveOrNegative).then(res=>{
        if(res.data.success){
          message.success('收藏成功')
        }
      })
    }
    else if(actionKey==="已收藏"){
      api.joinCollection('vrv-monitor-platform-web/collection/delete',this.id).then(res=>{
        if(res.data.success){
          message.success('取消成功')
        }
      })
    }else if(actionKey==="上传"){
      message.success('上传成功')
    }
    }
  markRead(item){
    console.log(item)

  }


  async changeResult1(type){
    let that = this;
    if(this.timer){
        clearTimeout(this.timer);
    }
    this.timer=setTimeout(()=>{
    that.setState({
        websiteType:type
      })
      that.webType()
      that.renderTabledata()
    },500)

  }
    //节流
    throttle(method,context){
      this.method.tId && clearTimeout(this.method.tId);
      this.method.tId=setTimeout(()=>{
          method.call(this)
      },300)
  }

  //改变类型type
  changeResult(type){
    let that = this;
    if(this.timer){
        clearTimeout(this.timer);
    }
    this.timer=setTimeout(()=>{
    that.setState({
        websiteType:type
      })
      that.webType()
      that.renderTabledata()
    },1000)
  }
  //分页
  async changeSize(value){
    await this.props.pageSize(value)
    await this.renderTabledata()
  }
  //删除多个
  deleData(){
    confirm({
      title: '提示',
      content: '确定删除吗',
      onOk: () => {
        if(this.state.deleteArr.length>0){
          this.props.dataDelete(this.state.deleteArr)
          message.success('删除成功')
          this.webType()
          this.renderTabledata()
          this.setState({
            deleteArr:[],
          })
        }else{
          message.success('请选择要删除的数据')
        }
    },
    onCancel() {
      return false
    }
    })
  }
  //删除单个
  hende(id){
    confirm({
      title: '提示',
      content: '确定删除吗',
      onOk: () => {
        this.props.dataDelete(id)
        message.success('删除成功')
        this.webType()
        this.renderTabledata()
    },
    onCancel() {
      return false
    }
    })
  }
  //导出
  exportSeles(){
    if(this.state.deleteArr.length>0){
      let sp = this.state.deleteArr.split(',').join(',')
      this.props.exportId(sp)
    }else{
      message.warning('请选择导出项');
    }
  }
  //批量标记已阅
  tagRead(){
    if(this.state.deleteArr.length>0){
      this.setState({
        ishas:true,
        ceshi:false
      })

      let readArr=[]
      this.state.deleteArr.split(',').forEach((item)=>{
        if(localStorage.read){
          let _readArr = localStorage.readingList;
          readArr=JSON.parse(_readArr);
          if(this.state.readArr.indexOf(item)===-1){
            readArr.push(item)
          }
        }else{
          if (readArr.indexOf(item)===-1) {
            readArr.push(item)
          }
        }
        let _readArr1 = JSON.stringify(readArr);
        localStorage.readingList = _readArr1
        this.setState({
          readArr:readArr
        })
      })
    }else{
      message.warning('请选择标记为已阅项');
    }
  }
  selectChange=(selectedRowKeys, selectedRows) => {
    let arr=selectedRowKeys.join(',')
    this.setState({
      deleteArr:arr
    })
    this.setState({selectedRowKeys});
    // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  };

  oninit(id){
    return false
  }
  //列表摘要
  abstract(){

  }
  //上传
  pExoort(){
    api.insert('vrv-monitor-platform-web/popularfeelingsDispose/insert', this.id, this.tit, this.content).then((res) => {
      if (res.data.success) {
        message.success('上传成功')
      }
    })
  }
  //点击分页
  async onChangecurrent(value){
    await this.setState({
      currentPage:value
    })
    await this.webType()
    await this.renderTabledata()
  }
  //相似文章编辑
  async assignField(value,value1){
    await this.setState({
      aggsField:value,
      searchType:value1
    })
    //await this.renderTabledata()
  }
  //定向检测
  renderdirec(){
    api.rendata('/vrv-monitor-platform-web/whitelist/queryByWebsite',1,10,'id','').then(res=>{
      if(res.data.success){
        let data=Object.assign([],res.data.data)
        let arr=[]
        data.map((d,index)=>(
          arr.push(d.website)
        ))
        this.setState({
          direcList:arr
        })
      }
    })
  }
  //筛选条件改变
  async taghandchange(arr){
    await this.props.tagchange(arr)
    await this.webType()
  }
  //已阅未阅
  hanchisread(value){
    this.setState({
      isRead:value
    })
  }
  render(){
    let tagListresult=this.state.tagList
    let Data=this.props.tableData
    let isreadarr=JSON.parse(localStorage.readingList)
    let arr1=[]
    let arr2=[]
      Data.map((d,index)=>{
        if(this.state.isRead===0){
        if(isreadarr.indexOf(d.id)!==-1){
          arr1.push(d)
          return Data=arr1
        }
      }
      else if(this.state.isRead===1){
        if(isreadarr.indexOf(d.id)===-1){
          arr2.push(d)
          return Data=arr2
        }
      }
      else{
        return Data
      }
      });
    const {selectedRowKeys} = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.selectChange
    };
    return(
      <div className="info-content">
        <div className="info-top">
          <TagList tagList={tagListresult} update={(result)=>this.condChange(result)} cleartypeall={this.props.tagchange}></TagList>
          <div className="filter-screen">
            <Row>
              <Col span={14}>
                <div className="left">
                  <div className="li">
                    <label>检测时间：</label>
                    <span><DatePicker onChange={this.onChange} defaultValue={moment(this.startTime())} /></span>
                    <span><TimePicker format="HH:mm" onChange={this.onChangestime}  defaultValue={moment('00:00','HH:mm')}></TimePicker></span>
                    <span className="interval">to</span>
                    <span><DatePicker onChange={this.onChangend} defaultValue={moment(this.endTime())}/></span>
                    <span><TimePicker format="HH:mm" defaultValue={moment(this.nowTime(),'HH:mm')}  onChange={this.onChangeendtime}></TimePicker></span>
                    <Button type="primary" onClick={()=>this.sureBtn()}>确定</Button>
                  </div>
                  <Tabchose  title={'情感倾向'} tabli={Tendency} onAdd={(result,value)=>{
                      this.posChange(value,0)
                    }} result={this.state.tagList} number='0'  choselist={this.props.choselist} tagchag={this.taghandchange}></Tabchose>
                  <Tabchose title={'浏览性'} tabli={browse} onAdd={(result)=>this.condChange(result)} result={this.state.tagList}  number='1' choselist={this.props.choselist} 
                    tagchag={this.taghandchange} changeabs={(value)=>this.hanchisread(value)}></Tabchose>
                  <Tabchose title={'查看模式'} tabli={chunk} onAdd={(result)=>this.condChange(result)} result={this.state.tagList}  number='2' 
                    choselist={this.props.choselist} tagchag={this.taghandchange} changeabs={(value)=>{this.setState({abstract:value})}}></Tabchose>
                </div>
              </Col>
              <Col span={10}>
                <div className="right">
                  <Tabchose title={'检测范围'} tabli={rangeCoury} onAdd={(result,value)=>this.posChange1(value,1)} result={this.state.tagList} number='3'  choselist={this.props.choselist} tagchag={this.taghandchange}></Tabchose>
                  <Tabchose title={'相似文章'} tabli={showoff} onAdd={(result)=>this.condChange(result)} result={this.state.tagList} number='4'  choselist={this.props.choselist} tagchag={this.taghandchange} assignField={(value,value1)=>this.assignField(value,value1)}></Tabchose>
                  <Tabchose title={'排序方式'} tabli={sortList} onAdd={(result,value)=>this.posChange2(value,3)} result={this.state.tagList} number='5'  choselist={this.props.choselist} tagchag={this.taghandchange}></Tabchose>
                  <Tabchose title={'定向检测'} typeid={"dir"} tabli={this.state.direcList} onAdd={(result)=>this.condChange(result)} result={this.state.tagList} number='6'  choselist={this.props.choselist} tagchag={this.taghandchange}></Tabchose>
                </div>
              </Col>
            </Row>
          </div>
        </div>
        <Taball tanList={this.props.switchlist} changereasult={(id)=>this.changeResult(id)}></Taball>
        <div className="table">
          <Table
          rowKey='id'
          click={this.tableAction}
          Abstract={this.state.abstract}
          onshow={this.oninit}
          data={Data}
          total={this.props.totals}
          pageSize={this.props.limit}
          rowSelection={rowSelection}
          changeSize={(value)=>this.changeSize(value)}
          deleteData={()=>this.deleData()}
          exportSeles={()=>this.exportSeles()}
          tagRead={()=>this.tagRead()}
          pExoort={this.pExoort}
          delete={(value)=>this.hende(value)}
          onChange={(currentpage)=>this.onChangecurrent(currentpage)}
          currentIndeX={this.state.currentPage}
          ishas={this.state.ishas}
          loading={this.props.loading}
          ></Table>
        </div>
      </div>
    )
  }
}

export default Info